// https://github.com/scottcorgan/tiny-emitter/blob/master/index.js
let EMITTER_INSTANCE = null;
class Emitter {
    constructor() {
        this.e = {};
    }

    static getInstance() {
        return EMITTER_INSTANCE ? EMITTER_INSTANCE : (EMITTER_INSTANCE = new Emitter());
    }
    static getName(event, id) {
        // const elementEvent = ['click', 'touchstart', 'touchmove', 'touchend', 'touchcancel'];
        // if (elementEvent.indexOf(event) !== -1) {
        //     return `element-${id}-${event}`;
        // }
        return `emitter-${event}-${id}`;
    }

    on(name, callback, ctx) {
        // console.log('------> ', ctx);
        let e = this.e || (this.e = {});
        (e[name] || (e[name] = [])).push({ callback, ctx });
        return this;
    }
    once(name, callback, ctx) {
        let listener = (...args) => {
            this.off(name, listener);
            callback.apply(ctx, args);
        };
        listener._ = callback;
        return this.on(name, listener, ctx);
    }
    emit(name, ...args) {
        // let data = [].slice.call(arguments, 1);
        let eventArr = (this.e[name] || []).slice();
        // name.indexOf('pointerdown') >= 0 && console.warn('[Emitter ] emit: ', name, ...args);
        eventArr.forEach(ele => ele.callback.call(ele.ctx, ...args));
        // eventArr.forEach(ele => ele.callback.call(ele.ctx, ...data));
        return this;
    }
    off(name, callback) {
        if (Object.prototype.toString.call(callback) === '[object Array]') {
            callback.forEach(func => this.off(name, func));
            return this;
        }
        let liveEvents = [];
        let obj = this.e;
        let eventArr = obj[name];
        if (eventArr && callback) {
            liveEvents = eventArr.filter(ele => ele.callback !== callback && ele.callback._ !== callback);
        }
        liveEvents.length ? (obj[name] = liveEvents) : delete obj[name];
        return this;
    }
}

export default Emitter;
